import Vue from 'vue'
import VueRouter from 'vue-router'
import {routes} from './routes'
Vue.use(VueRouter)
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'

const whiteList = ['/login','/homePage'] 


router.beforeEach(async(to, from, next) => {
  if (getToken() ) {
    NProgress.start()
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.name === '') {
        // 判断当前用户是否已拉取完user_info信息
       await store.dispatch('user/GetInfo').then(() => {
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
        }).catch(err => {
            store.dispatch('user/LogOut').then(() => {
              Message.error(err)
              next({ path: '/' })
            })
          })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
